package com.powerunion.datacollection.dao.impl;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.TargetsRolesDao;
import com.powerunion.datacollection.model.Role;
import com.powerunion.datacollection.model.Target;
import com.powerunion.datacollection.model.TargetsRoles;
import com.powerunion.datacollection.service.RoleManager;
import com.powerunion.datacollection.service.TargetManager;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;
import com.powerunion.util.query.jdbc.QueryParameters;

public class TargetsRolesDaoImpl extends JdbcBase implements TargetsRolesDao{
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			TargetsRolesDaoImpl.class);

	private RoleManager roleManager = new RoleManager();
	private TargetManager targetManager = new TargetManager();
	
	public boolean save (String[] tabIds,String roleId) throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}

		boolean isSuccess = false;
        String sql = "";
        List batchParams = null;

		try {

			batchParams = new ArrayList();
			sql = this.sqlInsert();
			for(int i=0; i<tabIds.length; i++) {
				TargetsRoles tr = this.findTargetsRolesByKey(tabIds[i], roleId);
				if(tr == null) {
					String id = String.valueOf(this.getSeq("tab_role"));
					String tabId = tabIds[i];
					QueryParameters param = new QueryParameters();
					param.addParameter(id, Types.VARCHAR);
					param.addParameter(tabId, Types.VARCHAR);
					param.addParameter(roleId, Types.VARCHAR);
					
					batchParams.add(param);
				}
			}
			
			this.executeBatch(sql, batchParams);
			
			isSuccess = true;
		} catch (Exception e) {
			logger.error("save:" + Constants.SAVE + "TabsRoles" + Constants.FAIL,e);
			return isSuccess;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("save:" + Constants.SAVE + "TabsRoles" + Constants.SUCCESS);
		}

		return isSuccess;

	}

	public TargetsRoles findTargetsRolesByKey(String targetId, String roleId) throws DaoException {
		String sql = this.sqlGetByKey();
		QueryParameters params = new QueryParameters();
		params.addParameter(targetId, Types.VARCHAR);
		params.addParameter(roleId, Types.VARCHAR);
		
		TargetsRoles tabsRoles = null;
		try {
			tabsRoles = (TargetsRoles) this.findByKey(sql, params, "getTargetsRoles");
		} catch (Exception e) {
			logger.error("findTargetsRolesByKey:" + Constants.SEARCH + "targetsRoles"
					+ Constants.FAIL,e);
			throw new DaoException("findTargetsRolesByKey:" + Constants.SEARCH + "tabsRoles"
					+ Constants.FAIL);
		}

		return tabsRoles;
	}

	public final TargetsRoles getTargetsRoles(ResultSet rs) throws Exception {
		TargetsRoles targetsRoles = new TargetsRoles();
		targetsRoles.setId(rs.getString("id"));
		
		Role role = roleManager.findRoleByKey(rs.getString("role_id"));
		targetsRoles.setRole(role);
		
		Target target = targetManager.findByKey(rs.getString("target_id"));
		targetsRoles.setTarget(target);

		return targetsRoles;
	}

	/**
	 * 根据角色主键删除与该角色有关的指标大类
	 * @param roleId
	 * @return
	 * @throws DaoException
	 */
	public boolean delete(String roleId) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "delete");
		boolean isSuccess = false;
		String[] codes  = new String[1];
		codes[0] = roleId;
		List batchParams = this.batchParams(codes, Types.VARCHAR);
		if (batchParams != null) {
			logger.error("delete:" + Constants.DELETE + "TargetsRoles"
					+ Constants.SUCCESS);
			try {
				this.executeBatch(this.sqlDelete(), batchParams);
				isSuccess = true;
			} catch (SQLException e) {
				logger.error("delete:" + Constants.DELETE + "TargetsRoles" + Constants.FAIL);
				logger.error(e.getMessage());
				return isSuccess;
			}
			
			return isSuccess;
		} else {
			return isSuccess;
		}
	}
	
	public List getTargetByRole(String roleId) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "getTargetByRole");
		
		String sql = "select target_id from dc_targets_roles where role_id = ? ";
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List list = null;
		try{
			list = new ArrayList();
			conn = this.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, roleId);
			rs = ps.executeQuery();
			while(rs.next()) {
				String tabId = rs.getString("target_id");
				list.add(tabId);
			}
		}catch(Exception e) {
			logger.error("getTargetByRole:" + Constants.SEARCH
			+ "tabIds" + Constants.FAIL);
			logger.error(e.getMessage());
			throw new DaoException("search db record error!");
		}finally{
			DBUtils.close(rs, ps, conn);
		}
		return list;
		
	}
	
	protected String sqlInsert() {
		StringBuffer sql = new StringBuffer();
		sql.append("insert into dc_targets_roles (id,target_id,role_id)")
		   .append(" values(?,?,?)");
		return sql.toString();
	}

	protected String sqlDelete() {
		StringBuffer sql = new StringBuffer();
		sql.append("delete from dc_targets_roles where role_id = ? ");
		return sql.toString();
	}
	
	protected String sqlGetByKey() {
		StringBuffer sql = new StringBuffer();
		sql.append(" select id,target_id,role_id from dc_targets_roles where target_id = ? and role_id = ? ");
		return sql.toString();
	} 
}
